import {createRouter, createWebHistory} from "vue-router";

import {getLoginStatus} from "@/api/LoginRequest.js";

import Page404 from "@/components/404.vue";
import Home from "@/views/Home.vue";
import Login from "@/views/user/Login.vue";
import OpinionAdd from "@/views/user/OpinionAdd.vue";

//配置导出路由
const routes = [
    {path: '/:pathMatch(.*)*', component: Page404, meta: {title: '404'}},
    {path: '/', component: Home, meta: {title: '首页'}},
    {path: '/login', component: Login, meta: {title: '登录'}},
    {path: '/upload-manager/upload-opinion', component: OpinionAdd, meta: {title: '上传意见', requireAuth: true}}
]

const router = createRouter({
    base: 'app',
    history: createWebHistory(),
    routes
})

/**
 * 路由错误回调
 */
router.onError((err, vm, info) => {
    console.log(`组件${vm.$vnode.tag}发生错误：${err.message},${info}`);
});


/**
 * 路由前置守卫
 */
router.beforeEach(async (to, from, next) => {
    window.document.title = to.meta.title === undefined ? '默认标题' : to.meta.title
    // 请求登录状态
    const login_status = await getLoginStatus();
    if (to.meta.requireAuth && !login_status.data) {
        // 跳转到登录页
        next('/login');
    } else {
        next();
    }
})

export default router